package cn.edu.zime.tjh.iotapp;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;

public class RegisterActivity extends AppCompatActivity {

    private EditText etUsername, etPassword, etConfirmPassword;
    private Button btnRegister;
    private TextView tvMessage;

    private final OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 初始化视图
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);
        btnRegister = findViewById(R.id.btnRegister);
        tvMessage = findViewById(R.id.tvMessage);

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();
                String confirmPassword = etConfirmPassword.getText().toString();

                // 验证输入
                if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
                    tvMessage.setText("用户名和密码不能为空");
                    tvMessage.setVisibility(View.VISIBLE);
                } else if (!password.equals(confirmPassword)) {
                    tvMessage.setText("两次输入的密码不一致");
                    tvMessage.setVisibility(View.VISIBLE);
                } else {
                    // 发起注册请求
                    register(username, password);
                }
            }
        });
    }

    private void register(String username, String password) {
        // 创建请求体
        RequestBody requestBody = new FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .build();

        // 创建请求对象
        Request request = new Request.Builder()
                .url("http://10.80.128.156:8080/user/register") // 替换为你的注册接口 URL
                .post(requestBody)
                .build();

        // 发起异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 处理请求失败
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvMessage.setText("网络请求失败，请检查网络连接");
                        tvMessage.setVisibility(View.VISIBLE);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 处理请求成功
                    String responseBody = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                // 解析服务器返回的 JSON 数据
                                JSONObject jsonResponse = new JSONObject(responseBody);
                                boolean success = jsonResponse.getBoolean("success");
                                String message = jsonResponse.getString("message");

                                if (success) {
                                    // 注册成功
                                    Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
                                    finish(); // 关闭注册界面
                                } else {
                                    // 注册失败
                                    tvMessage.setText(message);
                                    tvMessage.setVisibility(View.VISIBLE);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                tvMessage.setText("服务器返回数据格式错误");
                                tvMessage.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                } else {
                    // 处理请求失败
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvMessage.setText("注册失败，请重试");
                            tvMessage.setVisibility(View.VISIBLE);
                        }
                    });
                }
            }
        });
    }
}